//
//  ShoperDetailViewController.m
//  EasyToTesco
//
//  Created by mc on 16/2/22.
//  Copyright © 2016年 Jack. All rights reserved.
//   商品详情页面

#import "ShoperDetailViewController.h"
#import "ShoperDetailOneTableViewCell.h"
#import "ShoperDetailTwoTableViewCell.h"
//订单详情
//#import "OrderDetailViewController.h"
//商品简介
//#import "GoodsIntroViewController.h"
//lunbo

#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "CWStarRateView.h"
#import "NetWorkTools.h"
#import "CreatOrderViewController.h"
#import "ReadLoginData.h"
#import "StandardsView.h"
#import "QueRenDingDanViewController.h"
#import "XRCarouselView.h"

@interface ShoperDetailViewController ()<UITableViewDelegate, UITableViewDataSource,StandardsViewDelegate, XRCarouselViewDelegate>
{
    //判断是否显示全部评价
    BOOL judgeCell;
    NSString *EvaluationNum;
    UIView *ggView;
    
}
@property (nonatomic, strong)NSMutableDictionary *ShoperDetailDic;

@property (nonatomic, strong)UITableView *shopdetailtableview;
//存放图片的数组
@property (nonatomic, strong)NSMutableArray *picArray;

@property (nonatomic,strong)NSMutableDictionary *xingYingDict;

@property (nonatomic, strong) XRCarouselView *carouselView;

@property (nonatomic, assign) NSInteger num;

@end

@implementation ShoperDetailViewController

- (NSMutableDictionary *)xingYingDict {
    if (!_xingYingDict) {
        _xingYingDict = [NSMutableDictionary dictionary];
    }
    return _xingYingDict;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    [self ShoperDetailInitSomething];
    [self shoperdetailUI];
    [self ShoperDetailtableviewUI];
    
    [self addlastView];
    
    self.title = @"商品详情";
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.xingYingShopID.stringValue.length) {
        [self loadXingYingArrayData];
    }
}

- (void)loadXingYingArrayData {
    NSDictionary *dict = @{
                           @"ProductId":self.xingYingShopID
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTINFOQUERY" completeBlock:^(id object) {
        //        NSArray *array = [NetWorkTools arrayWithJsonString:[object objectForKey:@"BackData"]];
        self.xingYingDict = [[NetWorkTools arrayWithJsonString:[object objectForKey:@"BackData"]] firstObject];
        
        NSLog(@"%@",self.xingYingDict);
        
        [self.shopdetailtableview reloadData];
    }];
}
/**
 *  5
 */
- (void)ShoperDetailInitSomething {
    judgeCell = YES;
    EvaluationNum = @"156";
    self.picArray = [@[]mutableCopy];
    self.ShoperDetailDic = [[NSMutableDictionary alloc] initWithCapacity:0];
}

- (void)ShoperDetailtableviewUI{
    self.shopdetailtableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WEITH, HIGHT + 64) style:UITableViewStyleGrouped];
    self.shopdetailtableview.dataSource = self;
    self.shopdetailtableview.delegate = self;
    [self.view addSubview:self.shopdetailtableview];
}

- (void)shoperdetailUI {
    //    [self addShoperdetailtopView];
    
    
    [self addlastView];
}


- (void) addlastView {
    UIView *lastView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT - (HEIGHT * 0.1 - 20), WEITH, HIGHT*0.1 - 20)];
    [self.view addSubview:lastView];
    lastView.userInteractionEnabled = YES;
    lastView.backgroundColor = [UIColor blackColor];
    //    NSArray *array= @[@"加入订单", @"立即购买"];
    
    for (NSInteger i=0; i<2; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(WEITH/2 * i, 0, WEITH/2, lastView.frame.size.height);
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [button addTarget:self action:@selector(lastBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 330 + i;
        if (i == 1) {
            [button setTitle:@"立即购买" forState:UIControlStateNormal];
            button.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }else {
            [button setTitle:@"加入购物车" forState:UIControlStateNormal];
            button.backgroundColor = [UIColor colorWithRed:244/255. green:244/255. blue:244/255. alpha:1];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        //
        
        [lastView addSubview:button];
    }
}

- (void)lastBtnClick:(UIButton *)button {
    self.num = button.tag;
    if (button.tag == 331) {
        
        StandardsView *mystandardsView = [self buildStandardView:nil];
        mystandardsView.GoodDetailView = self.view;//设置该属性 对应的view 会缩小
        mystandardsView.showAnimationType = StandsViewShowAnimationShowFrombelow;
        mystandardsView.dismissAnimationType = StandsViewDismissAnimationDisFrombelow;
        [mystandardsView show];
        
    } else {
        StandardsView *mystandardsView = [self buildStandardView:nil];
        mystandardsView.GoodDetailView = self.view;//设置该属性 对应的view 会缩小
        mystandardsView.showAnimationType = StandsViewShowAnimationShowFrombelow;
        mystandardsView.dismissAnimationType = StandsViewDismissAnimationDisFrombelow;
        [mystandardsView show];
    }
}
//点击自定义按键
-(void)StandardsView:(StandardsView *)standardView CustomBtnClickAction:(UIButton *)sender
{
    if (sender.tag == 0) {
        
        [standardView dismiss];
    }
    else
    {
        if (self.num == 331) {
            
            QueRenDingDanViewController *qrVC = [[QueRenDingDanViewController alloc] init];
            
            qrVC.num = 0;
            
            qrVC.shopDic = [NSDictionary dictionary];
            qrVC.shopDic = @{@"Id":self.xingYingShopID,
                             @"buyNum":[NSString stringWithFormat:@"%ld", standardView.buyNum],
                             @"SellPrice":self.xingYingDict[@"SellPrice"],
                             @"Title":self.xingYingDict[@"Title"],
                             @"PictureURL":self.xingYingDict[@"PictureURL"]
                             };
            [standardView dismiss];
            [self.navigationController pushViewController:qrVC animated:YES];
            return;
        }
        NSDictionary *dic = @{
                              @"SellPrice":self.xingYingDict[@"SellPrice"],
                              @"Id":self.xingYingDict[@"Id"],
                              @"Title":self.xingYingDict[@"Title"],
                              @"buyNum":[NSString stringWithFormat:@"%ld", standardView.buyNum],
                              @"PictureURL":self.xingYingDict[@"PictureURL"],
                              @"isPay":@"0"
                              };
        NSMutableArray *arrayM = [NSMutableArray array];
        [arrayM addObjectsFromArray:[ReadLoginData readShopArr]];
        int i = 0;
        for (NSDictionary *dic1 in arrayM) {
            NSLog(@"%d", i);
            if (dic1[@"Id"] != dic[@"Id"]) {
                continue;
            }
            i ++;
        }
        if (i == 0) {
            [arrayM addObject:dic];
        } else {
            for (NSDictionary *dic1 in arrayM) {
                
                if (dic1[@"Id"] == dic[@"Id"]) {
                    [dic1 setValue:[NSString stringWithFormat:@"%ld", [dic1[@"buyNum"] integerValue] + standardView.buyNum] forKey:@"buyNum"];
                }
                
            }
        }
        [ReadLoginData saveShopDataToLocal:arrayM];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"加入购物车" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
        [standardView dismiss];
    }
    
    
}


//点击规格代理
-(void)Standards:(StandardsView *)standardView SelectBtnClick:(UIButton *)sender andSelectID:(NSString *)selectID andStandName:(NSString *)standName andIndex:(NSInteger)index
{
    if (sender.selected) {
        switch (index) {
                //            case 0:
                //                self.color = sender.titleLabel.text;
                //                break;
                //            case 1:
                //                self.size = sender.titleLabel.text;
                //                break;
                //            case 2:
                //                self.oneRate = sender.titleLabel.text;
                //            default:
                //                break;
                //        }
                //    } else {
                //        switch (index) {
                //            case 0:
                //                self.color = nil;
                //                break;
                //            case 1:
                //                self.size = nil;
                //                break;
                //            case 2:
                //                self.oneRate = nil;
                //            default:
                //                break;
        }
    }
    
    
    //NSLog(@"%@---%@---%@", self.color, self.size, self.oneRate);
    NSLog(@"--------%ld", standardView.buyNum);
    //  DLog(@"selectID = %@ standName = %@ index = %ld",selectID,standName,(long)index);
    
}
//设置自定义btn的属性
-(void)StandardsView:(StandardsView *)standardView SetBtn:(UIButton *)btn
{
    
#warning ---------修改商品规格返回确认按钮颜色！！！
    if (btn.tag == 0) {
        btn.backgroundColor = [UIColor whiteColor];
    }
    else if (btn.tag == 1)
    {
        btn.backgroundColor = [UIColor orangeColor];
    }
}
-(StandardsView *)buildStandardView:(NSString *)imgUrl {
    
    StandardsView *standview = [[StandardsView alloc] init];
    NSMutableArray *allArrM = [NSMutableArray array];
    //    standview.tag = index;
    standview.delegate = self;
    
    [standview.mainImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://120.76.162.124:8083%@", self.xingYingDict[@"PictureURL"]]]];
    standview.mainImgView.backgroundColor = [UIColor whiteColor];
    standview.priceLab.text = [NSString stringWithFormat:@"%@", self.xingYingDict[@"SellPrice"]];
    standview.tipLab.text = @"请选择规格";
    standview.goodNum.text = [NSString stringWithFormat:@"库存 %@件", self.xingYingDict[@"SecurityStock"]];
    
    
    standview.customBtns = @[@"返回",@"确定"];
    int i = 100;
    
    if ([self.xingYingDict[@"NormsNames"] length] != 0) {
        NSArray *normsArray = [self.xingYingDict[@"NormsNames"] componentsSeparatedByString:@";"];
        NSMutableArray *colorArrM = [NSMutableArray array];
        
        for (int i = 0; i < normsArray.count; i ++) {
            NSString *str = normsArray[i];
            if (i == (normsArray.count - 1)) {
                break;
            }
            standardClassInfo *colorClassInfo = [standardClassInfo StandardClassInfoWith:[NSString stringWithFormat:@"%@", str] andStandClassName:str];
            [colorArrM addObject:colorClassInfo];
        }
        
        StandardModel *tempModel = [StandardModel StandardModelWith:colorArrM andStandName:@"规格"];
        [allArrM addObject:tempModel];
    }
    
    
    standview.standardArr = allArrM;
    
    
    
    return standview;
}
//返回上一级页面


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 2;
    }else {
        if (judgeCell == YES) {
            return 2;
        } else {
            return 10;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *identifier = @"ShoperDetailOneTableViewCell";
        ShoperDetailOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ShoperDetailOneTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (self.xingYingShopID.stringValue.length) {
            cell.Titlelabel.text = [NSString stringWithFormat:@"%@",[self.xingYingDict objectForKey:@"Title"]];
            cell.pingpailabel.text = [NSString stringWithFormat:@"品牌"];
            cell.oldPriceLabel.text = [NSString stringWithFormat:@"库存数量:%@", self.xingYingDict[@"SecurityStock"]];
            cell.PriceNewLabel.text = [NSString stringWithFormat:@""];
            cell.SCpricelabel.text = [NSString stringWithFormat:@"市场价:%@",[self.xingYingDict objectForKey:@"SellPrice"]];
        } else {
            cell.Titlelabel.text = [NSString stringWithFormat:@"%@", self.ShoperDetailDic[@"title"]];
            cell.pingpailabel.text = [NSString stringWithFormat:@"品牌:%@", self.ShoperDetailDic[@"pinpai"]];
            cell.oldPriceLabel.text = [NSString stringWithFormat:@"库存数量:%@", self.ShoperDetailDic[@"kucun"]];
//            cell.PriceNewLabel.text = [NSString stringWithFormat:@"会员价:%@", self.ShoperDetailDic[@"huiyuanjia"]];
            cell.SCpricelabel.text = [NSString stringWithFormat:@"市场价:%@", self.ShoperDetailDic[@"shichangjia"]];
        }
        
        return cell;
        
    } else if (indexPath.section == 1) {
        static NSString *identifier = @"GoodsIntro";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = @"商品简介";
            
        } else {
            cell.textLabel.text = @"规格选择";
        }
        return cell;
    } else {
        static NSString *identifier = @"ShoperDetailTwoTableViewCell";
        ShoperDetailTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ShoperDetailTwoTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.shoperTwoPic.layer.cornerRadius = CGRectGetHeight(cell.shoperTwoPic.frame)/2;
            cell.shoperTwoPic.layer.masksToBounds = YES;
        }
        return cell;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 90;
    } else if (indexPath.section == 1) {
        return 30;
    } else {
        return 70;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return HIGHT/3;
    } else if (section == 1){
        return 0.01;
    } else {
        return 30;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 0;
    } else {
        return 10;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        
        [self addHeaderView:headerView];
        //        if (self.picArray.count!=0) {
        //            [self addSdcycleView:headerView];
        //        }
    } else {
        if (section == 1) {
            //            titlabel.text = @"商品简介";
        } else {
            
            UILabel *titlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 20)];
            titlabel.textAlignment = NSTextAlignmentLeft;
            titlabel.font = [UIFont systemFontOfSize:16];
            titlabel.textColor = [UIColor blackColor];
            [headerView addSubview:titlabel];
            titlabel.text = [NSString stringWithFormat:@"商品评价(%@)", EvaluationNum];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(CGRectGetMaxX(titlabel.frame)+10, 5, WEITH-CGRectGetMaxX(titlabel.frame)-10, 20);
            [button setTitle:@"加载更多评价" forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            button.titleLabel.textAlignment = NSTextAlignmentRight;
            [button setTitleColor:[UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(addjudgeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:button];
            
        }
        
    }
    return headerView;
}


- (void)addHeaderView:(UIView *)headerView {
    
    NSArray *images = @[[NSString stringWithFormat:@"http://120.76.162.124:8083%@", self.xingYingDict[@"PictureURL"]], [NSString stringWithFormat:@"http://120.76.162.124:8083%@", self.xingYingDict[@"PictureURL"]]];
    
    
    /**
     *  通过代码创建
     */
    self.carouselView = [XRCarouselView carouselViewWithImageArray:images describeArray:nil];
    
    //设置frame
    self.carouselView.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 3);
    
    //用代理处理图片点击，如果两个都实现，block优先级高于代理
    self.carouselView.delegate = self;
    
    
    //设置每张图片的停留时间
    _carouselView.time = 3;
    
    [headerView addSubview:_carouselView];
    
}

#pragma mark XRCarouselViewDelegate
- (void)carouselView:(XRCarouselView *)carouselView didClickImage:(NSInteger)index {
    NSLog(@"点击了第%ld张图片", index);
}




//判断是否加载更多的评价
- (void)addjudgeBtnClick:(UIButton *)button {
    if (judgeCell == YES) {
        [button setTitle:@"收回更多评价" forState:UIControlStateNormal];
    } else {
        [button setTitle:@"加载更多评价" forState:UIControlStateNormal];
    }
    
    judgeCell = !judgeCell;
    [self.shopdetailtableview reloadData];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] init];
    footView.backgroundColor = [UIColor grayColor];
    return footView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            //            GoodsIntroViewController *goodsIntroVC = [[GoodsIntroViewController alloc] init];
            //            goodsIntroVC.htmlStr = [NSString stringWithFormat:@"%@", self.ShoperDetailDic[@"about"]];
            //            [self presentViewController:goodsIntroVC animated:YES completion:nil];
        } else {
            //            [self addggViewUI];
        }
        
    }
}

- (void)addggViewUI {
    UITapGestureRecognizer * recognizer;
    // handleSwipeFrom 是偵測到手势，所要呼叫的方法
    recognizer = [[UITapGestureRecognizer alloc] initWithTarget:nil action:@selector(tapclick)];
    // 不同的 Recognizer 有不同的实体变数
    // 例如 SwipeGesture 可以指定方向
    // 而 TapGesture 則可以指定次數
    
    [self.view addGestureRecognizer:recognizer];
    
    ggView = [[UIView alloc] initWithFrame:CGRectMake(0, ((HIGHT*0.9)/3)*2, WEITH, (HIGHT*0.9)/3)];
    ggView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:ggView];
}

- (void)tapclick {
    [ggView removeFromSuperview];
}


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
